<?php

namespace App\Modules\Post\Admin\Controllers;

use App\Modules\Post\Models\PostCate;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Arr;
use Encore\Admin\Form;
use Encore\Admin\Grid;
use Encore\Admin\Show;
use Encore\Admin\Tree;
use Encore\Admin\Widgets\Box;
use Encore\Admin\Layout\Row;
use Encore\Admin\Layout\Column;
use Encore\Admin\Layout\Content;
use App\Admin\Controllers\BaseController;

class PostCateController extends BaseController
{
    protected $title = '文章分类管理';
    //protected $mslug = 'app.post';
    protected $desc = ['index' => '列表', 'edit' => '编辑', 'create' => '新建', 'show' => '详情'];

    public function __construct()
    {
        $this->model = new PostCate();
        $this->module = get_module_by_class($this->model);
    }

    public function index(Content $content)
    {
        $this->table = $table = $this->model->getTable();
        $this->sets = $sets = (new \App\Models\Set())->where('name', $table . '.' . get_class($this->model))->first();
        if (empty($sets)) {
            $sets = config('tables.' . $table . '.sets_form_default');
            $seturl = route('admin.set.create', ['name' => $table . '.' . get_class($this->model)]);
        } else {
            $seturl = route('admin.set.edit', ['set' => $sets->id]);
        }
        $this->desc['index'] = "<a href='{$seturl}'>设置</a>";

        return $content
            ->breadcrumb(['text' => $sets['title'] . '管理'])
            ->title($sets['title'] . '管理')
            ->description($this->desc['index'] ?? trans('admin.list'))
            ->row(function (Row $row)  use ($model, $sets) {
                $row->column(6, $this->treeView()->render());
                $row->column(6, function (Column $column) use ($model, $sets) {    //create部分

                    $form = new \Encore\Admin\Widgets\Form($model);
                    $form->action(route('admin.post.postcate.store'));
                    //不允许生成或修改时改变parent_id,防止次序混乱

                    $form->text('title', '分类名')->rules('required');
                    $form->text('name', '标识')->rules('required');
                    if (empty($sets['disable_group'])) {
                        $form->tags('groups', '分组');
                    }
                    if (empty($sets['disable_publish'])) {
                        $form->switch('publish', '允许发布')->default(1)->states([
                            'on'  => ['value' => 1, 'text' => '是'],
                            'off' => ['value' => 0, 'text' => '否'],
                        ]);
                    }
                    $column->append((new Box(trans('admin.new'), $form))->style('success'));
                });
            });

        return $content
            ->title($this->title())
            ->description($this->desc['index'] ?? trans('admin.list'))
            ->body($this->grid());
    }
}
